package jp.tkym.labs.store;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import jp.tkym.labs.store.query.BeanQuery;
import jp.tkym.labs.store.sql.PreparedStatementExecutor;
import jp.tkym.labs.store.sql.SqliteBeanQuery;
import jp.tkym.labs.store.sql.SqliteBeanstore;
import jp.tkym.labs.store.sql.SqliteMaster;

class SqliteBeanstoreService implements BeanstoreService{
	private Connection connection;
	private Map<Class<?>, Beanstore<?>> storeMap;
	private PreparedStatementExecutor executor;
	
	public static void setup(){
		try {
			Class.forName(SqliteBeanstoreServiceFactory.class.getName());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	SqliteBeanstoreService(Connection connection){
		this.connection = connection;
		storeMap = new ConcurrentHashMap<Class<?>, Beanstore<?>>();
		executor = new PreparedStatementExecutor(connection);
	}
	
	@Override
	public void commit()throws BeanstoreException{
		try {
			connection.commit();
		} catch (SQLException e) {
			throw new BeanstoreException(e);
		}
	}
	
	@Override
	public void rollback() throws BeanstoreException {
		try {
			connection.rollback();
		} catch (SQLException e) {
			throw new BeanstoreException(e);
		}
	}
	
	@Override
	public <B> BeanQuery<B> query(Class<B> cls){
		return new SqliteBeanQuery<B>(cls, executor);
	}

	@Override
	public <B> Beanstore<B> store(Class<B> cls){
		Beanstore<B> store = getStore(cls);
		if(store == null){
			store = new SqliteBeanstore<B>(cls, executor);
			storeMap.put(cls, store);
		}
		return store;
	}
	
	@SuppressWarnings("unchecked")
	private <B> Beanstore<B> getStore(Class<B> cls){
		return (Beanstore<B>)storeMap.get(cls);
	}

	@Override
	public void close() throws BeanstoreException {
		try {
			connection.close();
		} catch (SQLException e) {
			throw new BeanstoreException(e);
		}
	}
}